package com.wb.utils

import com.wb.component.Slf4j
import com.wb.component.Slf4j.Companion.log
import com.gargoylesoftware.htmlunit.BrowserVersion
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.html.DomElement
import com.gargoylesoftware.htmlunit.html.HtmlElement
import com.gargoylesoftware.htmlunit.html.HtmlPage
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.jsoup.Jsoup
import java.net.URLDecoder
import java.nio.charset.Charset
import java.util.*
import kotlin.collections.HashMap

/**
 * 磁力链接工具
 *
 * @author 祁雪
 */
@Slf4j
class MagnetUtil {

    companion object {

        /**
         * 搜索
         * @param key
         * @param random
         */
        fun search(key: String, random: Boolean): HashMap<String, String>? {

            try {

                println("开始搜索${key}相关磁力种子")
                var dom = Jsoup.connect("https://0magnet.com/search?q=${key}")
                    .get()


                if (dom == null) {
                    return null
                }
                val items = dom.select(".file-list a")

                if (items.isNullOrEmpty()) {
                    return null
                }

                var index = 0
                if (random) {
                    index = (Math.random() * items.size).toInt()
                }
                val infoUrl = "https://0magnet.com${items.get(index).attr("href")}"
                println("开始访问:${infoUrl}")

                dom = Jsoup.connect(infoUrl).get()

                if (dom == null) {
                    return null
                }

                val title = dom.selectFirst(".magnet-title").text()

                val magnetUrl = dom.selectFirst("#input-magnet").`val`()

                val hashUrl = magnetUrl.substring(0, magnetUrl.indexOf("&"))

                return hashMapOf(
                    "title" to title,
                    "magnetUrl" to magnetUrl,
                    "hashUrl" to hashUrl
                )
            } catch (e: Exception) {
                log.error("磁力搜索出错", e)
            }

            return null
        }

        fun searchByTokyotosho(key: String, random: Boolean): HashMap<String, String>? {

            try {

                println("开始搜索${key}相关磁力种子")
                val dom =
                    Jsoup.connect("https://www.tokyotosho.info/search.php?terms=${key}&type=0&searchName=true&searchComment=true&size_min=&size_max=&username=")
                        .get()

                if (dom == null) {
                    return null
                }
                println("磁力搜索完成, 开始提取")

                val items = dom.select(".listing .desc-top")

                val list = arrayListOf<HashMap<String, String>>()

                items.forEach {
                    if (it.select("a").size >= 2) {
                        val hashUrl = it.selectFirst("a").attr("href").split("&")[0]
                        val title = it.text()
                        // val torrentUrl = it.getElementsByAttribute("type").attr("href")
                        // println("hash: ${hashUrl}\t${title}\t${torrentUrl}")
                        list.add(
                            hashMapOf(
                                "title" to title,
                                "hashUrl" to hashUrl
                            )
                        )
                    }
                }

                if (list.size == 0) return null

                val index = if (random) {
                    (Math.random() * list.size).toInt()
                } else {
                    0
                }

                return list[index]

            } catch (e: Exception) {
                log.error("磁力搜索出错", e)
            }
            return null;
        }

        fun searchSoucili(key: String, random: Boolean, one: Boolean): HashMap<String, String>? {

            try {

                val page = ((Math.random() * 10)).toInt()
                println("随机访问soucili.info第${if (one) 0 else page}页")
                val responseStr = RestUtil.send(
                    "https://soucili.info/request/",
                    hashMapOf(
                        "request_type" to "esearch_v11",
                        "keywords" to key,
                        "device_id" to UUID.randomUUID().toString(),
                        "page" to (if (one) 0 else page).toString()
                    ),
                    null,
                    1,
                    String::class.java
                ).body

                val gson = Gson()
                if (responseStr != null) {
                    val response = gson.fromJson(
                        responseStr,
                        object : TypeToken<HashMap<String, Any>>() {}.type
                    ) as HashMap<String, Any>
                    if (response.containsKey("videos")) {
                        val videos = gson.fromJson(
                            gson.toJson(response.get("videos")),
                            object : TypeToken<List<Map<String, String>>>() {}.type
                        ) as List<Map<String, String>>?

                        if (videos != null && videos.size > 0) {

                            val index = if (random) {
                                (Math.random() * videos.size).toInt()
                            } else {
                                0
                            }

                            return hashMapOf(
                                "title" to videos[index].getOrDefault("file_name", ""),
                                "hashUrl" to "magnet:?xt=urn:btih:${videos[index].getOrDefault("moc", "")}"
                            )
                        } else {
                            return if (one) null else searchSoucili(key, random, true)
                        }
                    }

                }
                return if (one) null else searchSoucili(key, random, true)

            } catch (e: Exception) {
                log.error("磁力搜索出错", e)
            }
            return null
        }

        fun searchCLM(key: String, random: Boolean, one: Boolean): HashMap<String, String>? {

            try {
                // 如访问失效 需要去 磁力猫.com 找最新访问稳定的地址
                val page = ((Math.random() * 10) + 1).toInt()
                println("访问磁力猫.com第${if (one) 1 else page}页")

                val dom = Jsoup.connect(
                    "https://clm229.xyz/search-${key}-0-4-${
                        if (one) 1 else page
                    }.html"
                ).get()

                val items = dom.select(".ssbox")

                val list = arrayListOf<HashMap<String, String>>()

                if (items.isNullOrEmpty()) {
                    return if (one) null else searchCLM(key, random, true)
                }

                items.forEach {
                    list.add(
                        hashMapOf(
                            "title" to it.select(".title a").text(),
                            "hashUrl" to it.select(".sbar").select("a").first().attr("href")
                        )
                    )
                }

                return if (random) list.get((Math.random() * list.size).toInt()) else list[0]

            } catch (e: Exception) {
                log.error("磁力搜索出错", e)
            }
            return null
        }

    }

}

fun main() {
    println(MagnetUtil.searchSoucili("永劫无间", false, false))
}